package model

import (
	"errors"
	"haodayizhi/global"

	"gorm.io/gorm"
)

const TableNameUserTag = "user_tags"

// UserTag mapped from table <user_tags>
type UserTag struct {
	ID     int64  `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id,string"`
	UserID int64  `gorm:"column:user_id;type:bigint" json:"userId"`
	Tag    string `gorm:"column:tag;type:varchar(50)" json:"tag"`
}

// TableName UserTag's table name
func (*UserTag) TableName() string {
	return TableNameUserTag
}

// CreateUserTag creates a new UserTag in the database.
func (m *UserTag) CreateUserTag() error {
	if err := global.Db.Create(m).Error; err != nil {
		return err
	}
	return nil
}

// GetUserTagByID retrieves a UserTag by its ID from the database.
func (m *UserTag) GetUserTagByID(id int64) (*UserTag, error) {
	result := global.Db.First(m, id)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, nil // UserTag not found
		}
		return nil, result.Error
	}
	return m, nil
}

// UpdateUserTag updates an existing UserTag in the database.
func (m *UserTag) UpdateUserTag() error {
	if err := global.Db.Save(m).Error; err != nil {
		return err
	}
	return nil
}

// DeleteUserTag deletes a UserTag by its ID from the database.
func (m *UserTag) DeleteUserTag(id int64) error {
	if err := global.Db.Delete(m, id).Error; err != nil {
		return err
	}
	return nil
}
